// pages/Product/Product.js
import {
  getProductDetailInfoByProductId,
  getProductParameterInfoByProductId,
} from "../../service/product";
import Decimal from "decimal.js";
import {
  queryIsFavoriteProduct,
  addProductToCollection,
  removeProductFavorite,
} from "../../service/collection";

import {
  queryDefaultDeliveryAddress
} from "../../service/delivery-address";

import {
  addShippingCart
} from "../../service/shipping-cart";
import dayjs from 'dayjs'
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 商品Id
    productId: 0,
    // 商品的小tip
    productTip: "",
    // 商品轮播图
    bannerImages: [],
    // banner图目前的索引
    bannerCurrentIndex: 0,
    // 品牌名称
    brandName: "",
    // 品牌ID
    brandId:null,
    // 商品详情图
    detailImages: [],
    // 商品名称
    productName: "",
    // 商品规格列表
    specificationList: [],
    // 是否展示购物车
    showShppingCart: false,
    // 展示立即购买
    showBuyNow: false,
    // 展示商品参数
    showParameter: false,
    // 展示注册证件照
    showRegistration: false,
    // 商品是否已收藏
    isFavorite: false,
    // 用户收货地址
    userAddress: null,
    // 当前选中的规格（默认为第一个规格）
    activeSpecificationIndex: 0,
    // stepper的值
    stepperValue: 1,
    // 商品参数
    parameter: null,
    // 商品总价
    sumPrice: 0,
    // 商品类型
    productType: 0,
    // 秒杀开始时间
    seckillStartTime: null,
    // 秒杀结束时间
    seckillEndTime: null,
    // 距离结束还有多少毫秒
    countDownTime: null,
    countDownTimeData: {},
    // 总库存
    stock: 0,
    // 可用库存
    availableStock: 0,
    // 生产日期
    manufactureDate: null,
    // 有效期
    expirationDate: null
  },
  /**
   *  秒杀倒计时处理函数
   */
  onCountDownChange(event) {
    this.setData({
      countDownTimeData: event.detail
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const productId = options.productId;
    const res = await getProductDetailInfoByProductId(productId);
    if (app.globalData.isLogin) {
      const res = await queryIsFavoriteProduct(productId);
      this.setData({
        isFavorite: res.data,
      });
    }
    this.setData({
      productId: productId,
      productTip: res.data.productTip,
      productName: res.data.productName,
      detailImages: res.data.detailImageUrls.split(","),
      bannerImages: res.data.bannerImageUrls.split(","),
      specificationList: res.data.specificationVoList,
      brandName: res.data.brandName,
      productType: res.data.productType,
      seckillStartTime: res.data.seckillStartTime,
      seckillEndTime: res.data.seckillEndTime,
      stock: res.data.stock,
      availableStock: res.data.availableStock,
      manufactureDate: res.data.manufactureDate,
      expirationDate: res.data.expirationDate,
      brandId:res.data.brandId
    });
    if (this.data.productType === 1) {
      const now = dayjs(); // 当前时间
      const targetTime = dayjs(res.data.seckillEndTime); // 未来时间
      const remainingMs = targetTime.valueOf() - now.valueOf();
      const finalRemainingMs = Math.max(remainingMs, 0);
      this.setData({
        countDownTime: finalRemainingMs
      })
    }
    if (this.data.productType === 0) {
      this.setData({
        sumPrice: this.data.specificationList[this.data.activeSpecificationIndex].discountPrice,
      });
    } else if (this.data.productType === 1) {
      this.setData({
        sumPrice: this.data.specificationList[this.data.activeSpecificationIndex].seckillPrice,
      });
    } else {
      this.setData({
        sumPrice: this.data.specificationList[this.data.activeSpecificationIndex].promotionPrice,
      });
    }

    const flag = options.showShippingCart;
    const self = this;
    if (flag) {
      setTimeout(() => {
        self.setData({
          showShppingCart: true,
        });
      }, 500);
    }
    console.log(this.data);
  },
  /**
   * banner图变化
   */
  onSwiperChange(event) {
    const index = event.detail.current;
    this.setData({
      bannerCurrentIndex: index,
    });
  },
  /**
   * 点击立即购买按钮
   */
  async onTapBuyNow() {
    const deliveryAddress = await queryDefaultDeliveryAddress();
    this.setData({
      showBuyNow: true,
      userAddress: deliveryAddress.data,
    });
  },
  /**
   * 点击品牌按钮
   */
  onTapBrand() {
    if(this.data.brandId){
      wx.navigateTo({
        url: `/pages/BrandDetail/BrandDetail?brandId=${this.data.brandId}`,
      })
    }
  },

  /**
   * 点击注册证件照
   */
  async onTapRegistration() {
    this.setData({
      showRegistration: true,
    });
    if (this.data.parameter === null) {
      const res = await getProductParameterInfoByProductId(this.data.productId);
      this.setData({
        parameter: res.data,
      });
    }
  },
  /**
   * 点击加入购物车按钮
   */
  onTapShippingCart() {
    this.setData({
      showShppingCart: true,
    });
  },
  /**
   * 点击PopUp的关闭按钮
   */
  onTapClose() {
    this.setData({
      // 是否展示购物车
      showShppingCart: false,
      // 展示立即购买
      showBuyNow: false,
      // 展示商品参数
      showParameter: false,
      // 展示注册证件照
      showRegistration: false,
    });
    const that = this;
    setTimeout(() => {
      that.setData({
        stepperValue: 1,
        activeSpecificationIndex: 0,
      });
    }, 100);
  },
  /**
   * 点击收藏按钮
   */
  async onTapFavoriteButton() {
    if (this.data.isFavorite) {
      // 取消商品收藏
      await removeProductFavorite(this.data.productId);
      wx.showToast({
        title: "取消收藏成功",
        icon: "none",
        duration: 1000,
      });
    } else {
      // 添加商品收藏
      await addProductToCollection(this.data.productId);
      wx.showToast({
        title: "您已收藏商品，可去“我的-我的收藏”页面查看哦",
        icon: "none",
        duration: 1000,
      });
    }
    this.setData({
      isFavorite: !this.data.isFavorite,
    });
  },
  /**
   * 点击导航到购物车页面
   */
  onTapNavigatorToShippingCart() {
    wx.switchTab({
      url: "/pages/ShippingCart/ShippingCart",
    });
  },
  /**
   * 点击收货地址按钮
   */
  onTapAddress() {
    const self = this;
    wx.navigateTo({
      url: "/pages/DeliveryAddress/DeliveryAddress",
      events: {
        selectDeliveryAddress(data) {
          console.log("接受到数据", data);
          self.setData({
            userAddress: data,
          });
        },
      },
    });
  },
  /**
   * 点击新增收货地址
   */
  onTapAddDeliveryAddress() {
    const self = this;
    wx.navigateTo({
      url: "/pages/DeliveryAddress/AddDeliveryAddress/AddDeliveryAddress",
      events: {
        selectDeliveryAddress(data) {
          console.log(data);
          self.setData({
            userAddress: data,
          });
        },
      },
    });
  },
  /**
   * 点击stepper
   */
  onTapStepper(event) {
    let price = 0
    if (this.data.productType === 0) {
      // 普通商品
      price = new Decimal(
          this.data.specificationList[this.data.activeSpecificationIndex].discountPrice
        )
        .times(event.detail)
        .toString();
    } else if (this.data.productType === 1) {
      // 秒杀商品
      price = new Decimal(
          this.data.specificationList[this.data.activeSpecificationIndex].seckillPrice
        )
        .times(event.detail)
        .toString();
    } else {
      price = new Decimal(
          this.data.specificationList[this.data.activeSpecificationIndex].promotionPrice
        )
        .times(event.detail)
        .toString();
    }
    this.setData({
      stepperValue: event.detail,
      sumPrice: price,
    });
  },
  /**
   * 点击付款按钮
   */
  onTapPayment() {},
  /**
   * 点击某个规格项
   */
  onTapSpecificationOption(event) {
    const index = event.target.dataset.index;
    let price = 0
    if (this.data.productType === 0) {
      price = this.data.specificationList[index].discountPrice
    } else if (this.data.productType === 1) {
      price = this.data.specificationList[index].seckillPrice
    }

    this.setData({
      activeSpecificationIndex: index,
      stepperValue: 1,
      sumPrice: price,
    });
  },
  /**
   * 点击商品参数
   */
  async onTapParameter() {
    this.setData({
      showParameter: true,
    });
    if (this.data.parameter === null) {
      const res = await getProductParameterInfoByProductId(this.data.productId);
      console.log(res);
      this.setData({
        parameter: res.data,
      });
    }
  },
  /**
   * 查看注册证件照
   */
  async queryRegistration() {
    const pdf = this.data.parameter.registrationIdPhoto;
    if(!pdf){
      wx.showToast({
        title: '暂无注册证件照',
      })
    }
    wx.showLoading({
      title: "加载中",
    });
    wx.downloadFile({
      url: pdf,
      success: (res) => {
        wx.hideLoading();
        console.log(res);
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            fileType: "pdf",
            success: () => {},
            fail: (err) => {
              wx.showToast({
                title: "PDF预览失败",
                icon: "none",
              });
            },
          });
        } else {
          wx.showToast({
            title: "文件下载失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: "文件下载失败",
          icon: "none",
        });
      },
    });
  },
  /**
   * 点击预览照片
   */
  onTapPreviewImage(event) {
    // 调用微信预览图片接口
    wx.previewImage({
      current: event.currentTarget.dataset.imgurl, // 当前显示图片的http链接
      urls: this.data.bannerImages, // 需要预览的图片http链接列表
    });
  },
  /**
   * 点击预览规格项图片
   */
  onTapProductSketchImage(event) {
    const currentSrc = event.currentTarget.dataset.imgUrl;
    const images = [currentSrc];
    // 调用微信预览图片接口
    wx.previewImage({
      current: currentSrc, // 当前显示图片的http链接
      urls: images, // 需要预览的图片http链接列表
    });
  },
  /**
   * 添加商品到购物车
   */
  async onTapAddToShippingCart() {
    const specificationId = this.data.specificationList[
      this.data.activeSpecificationIndex
    ].id;
    const count = this.data.stepperValue;
    const param = {
      productId: this.data.productId,
      productSpecificationId: specificationId,
      quantity: count,
    };
    wx.showLoading({
      title: "加载中",
    });
    await addShippingCart(param);
    wx.hideLoading();
    wx.showToast({
      title: "成功添加商品至购物车",
      icon: "none",
    });
    this.setData({
      showShppingCart: false,
    });
  },
});